<template>
  <router-view />
</template>

<script setup>
import { useAuthStore } from '@/store/auth'
import { onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'

const authStore = useAuthStore()
const router = useRouter()

// 修复路由守卫逻辑
const checkAuth = () => {
  const token = authStore.token
  const currentRoute = router.currentRoute.value

  // 允许未登录用户访问的页面
  const publicPaths = ['/login', '/register'];

  // 检查当前路由是否需要认证
  const requiresAuth = currentRoute.matched.some(record => record.meta.requiresAuth)

  if (!token && requiresAuth) {
    // 未登录且访问需要认证的页面 -> 重定向到登录
    router.push('/login')
  } else if (token && publicPaths.includes(currentRoute.path)) {
    // 已登录但访问登录/注册页面 -> 重定向到首页
    router.push('/')
  }
}

// 初始检查
onMounted(() => {
  checkAuth()
})

// 监听路由变化
watch(() => router.currentRoute.value, (newRoute) => {
  checkAuth()
}, { deep: true })
</script>

<style>
#app {
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #333;
  min-height: 100vh;
  background-color: #f5f7fa;
}
</style>